package com.example.service;

import com.example.mapper.MenuMapper;
import com.example.mapper.MenuRoleMapper;
import com.example.model.Hr;
import com.example.model.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 创建人: 麦健豪
 * 创建日期: 2020/9/20 0:37
 */
@Service
public class MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    MenuRoleMapper menuRoleMapper;

    public List<Menu> getMenusByHrId() {
        return menuMapper.getMenusByHrId(
                ((Hr) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId()
        );
    }

    public List<Menu> getAllMenusWithRole() {
        return menuMapper.getAllMenusWithRole();
    }

    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }

    public List<Integer> getMidsByRid(Integer rid) {
        return menuMapper.getMidsByRid(rid);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateMenuRole(Integer rid, Integer[] mids) {
        menuRoleMapper.deleteByRid(rid);
        if (mids.length == 0) {
            //mids为空,只需删除menu_role中rid mid 的映射关系
            return true;
        } else {
            Integer result = menuRoleMapper.insertRecord(rid, mids);
            return result == mids.length;
        }
    }

}
